
package com.vichat.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.vichat.common.cache.LocalCacher;
import com.vichat.common.cache.RedisHelper;
import com.vichat.common.constant.GlobalConstant;
import com.vichat.common.constant.I18nConstant;
import com.vichat.common.enums.RecordType;
import com.vichat.common.exception.ViChatException;
import com.vichat.common.signal.CmdUtil;
import com.vichat.common.util.*;
import com.vichat.common.vo.Grid;
import com.vichat.common.vo.Json;
import com.vichat.common.vo.PageFilter;
import com.vichat.common.vo.ZTree;
import com.vichat.res.entity.ResEvent;
import com.vichat.res.entity.ResFile;
import com.vichat.res.entity.RoomMicRecordDLog;
import com.vichat.res.entity.SysRecord;
import com.vichat.res.service.ICfgService;
import com.vichat.res.service.IResService;
import com.vichat.res.vo.ResFileVO;
import com.vichat.res.vo.VichatRoomRecResVO;
import com.vichat.room.entity.RoomBasic;
import com.vichat.room.service.IRoomService;
import com.vichat.user.cache.StaticDataCache;
import com.vichat.user.entity.*;
import com.vichat.user.service.ISecService;
import com.vichat.user.service.IStaticDataService;
import com.vichat.user.service.ISystemMessageService;
import com.vichat.user.service.IUserService;
import com.vichat.user.threads.RefreshUserThread;
import com.vichat.user.vo.UserBasicVO;
import com.vichat.user.vo.UserCompanyVO;
import com.vichat.user.vo.UserOnlineVO;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.asn1.x509.UserNotice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by ranjx on 2017/10/18.
 */
@Controller
@RequestMapping("/vcapi")
public class VCApiController extends BaseController {

    private static Logger logger = LoggerFactory.getLogger(VCApiController.class);
    ExecutorService tp = Executors.newCachedThreadPool();
    @Autowired
    HttpServletRequest request;
    @Autowired
    HttpServletResponse response;
    @Autowired
    private IUserService userService;
    @Autowired
    private IStaticDataService staticDataService;
    @Autowired
    private IRoomService roomService;
    @Autowired
    private IResService resService;
    @Autowired
    private ICfgService cfgService;
    @Autowired
    private ISecService secService;
    @Autowired
    private ISystemMessageService systemMessageService;


    /**
     * 保存子账号
     *
     * @param user
     * @return
     */
    @RequestMapping("/saveUser")
    @ResponseBody
    public Json saveUser(UserBasic user) {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            long partyId = sessionUser.getPartyId();
            long orgId = sessionUser.getOrgId();
            user.setPartyId(partyId);

            if (NumberUtils.isNullOrZero(user.getOrgId())) {
                user.setOrgId(orgId);
            }

            if (NumberUtils.isNotNullOrZero(user.getUid())) {
                UserBasic userFDB = userService.getUserBasicByUid(user.getUid());
                if (!StringUtils.equals(userFDB.getUserName(), user.getUserName())) {
                    roomService.updateUserName(userFDB.getUid(), user.getUserName());
                }
            }
            String opedInfo = "";
            if (NumberUtils.isNotNullOrZero(user.getUid())) {
                opedInfo = "修改用户:" + user.getUserName();
            } else {
                opedInfo = "添加用户:" + user.getUserName();
            }
            userService.saveSysBusiRecord(sessionUser, RecordType.WEBUSER, user.getUid(), user.getUserName(), opedInfo, opedInfo);

            userService.saveUserBasic(user);
            userService.updateUserBasicVersion(user.getUid());
            tp.execute(new RefreshUserThread(userService, partyId, GlobalConstant.REFRESH_TYPE_USER));
            json.setObj(user);
            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }


    /**
     * 批量保存子账号
     *
     * @param userBasics
     * @return
     */
    @RequestMapping("/batchSaveUser")
    @ResponseBody
    public Json batchSaveUser(@RequestBody List<UserBasic> userBasics) {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            long partyId = sessionUser.getPartyId();
            long orgId = sessionUser.getOrgId();
            if (!userBasics.isEmpty()) {
                for (UserBasic userBasic : userBasics) {
                    if (NumberUtils.isNullOrZero(userBasic.getOrgId())) {
                        userBasic.setOrgId(orgId);
                    }
                    userBasic.setPartyId(partyId);
                    userService.saveUserBasic(userBasic);
                }
            }
            tp.execute(new RefreshUserThread(userService, partyId, GlobalConstant.REFRESH_TYPE_USER));
            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 删除用户信息
     *
     * @param uid
     * @return
     */
    @RequestMapping("/deleteUser")
    @ResponseBody
    public Json deleteUser(long uid) {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            UserBasic userFDB = userService.getUserBasicByUid(uid);
            if (userFDB.getPartyId().longValue() == sessionUser.getPartyId().longValue()) {
                userService.delUserBasic(sessionUser.getPartyId(), uid);

                if (GlobalConstant.SUPPORT_ADMIN_LOGIN_APP) {
                    roomService.delRoomMemberLogicallyByUid(uid);
                }
                userService.updateUserBasicVersion(userFDB.getUid());
                String uname = RedisHelper.getUname(uid);
                String opedInfo = "delete user:" + uname;
                userService.saveSysBusiRecord(sessionUser, RecordType.WEBEXPIREDDATE, uid, uname, opedInfo, opedInfo);
            }
            CmdUtil.sendImMsg(10000, userFDB.getUid(), 0, GlobalConstant.IMS_REMOVE_STOP, "");

            tp.execute(new RefreshUserThread(userService, sessionUser.getPartyId(), GlobalConstant.REFRESH_TYPE_USER));
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 停用用户信息
     *
     * @param uid
     * @return
     */
    @RequestMapping("/stopUser")
    @ResponseBody
    public Json stopUser(long uid) {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            UserBasic userFDB = userService.getUserBasicByUid(uid);
            if (userFDB.getPartyId().longValue() == sessionUser.getPartyId().longValue()) {
                userService.stopUserBasic(sessionUser.getPartyId(), uid);
//                roomService.delRoomMemberLogicallyByUid(uid);
                userService.updateUserBasicVersion(userFDB.getUid());
                String uname = RedisHelper.getUname(uid);
                String opedInfo = "stop user:" + uname;
                userService.saveSysBusiRecord(sessionUser, RecordType.WEBEXPIREDDATE, uid, uname, opedInfo, opedInfo);
                CmdUtil.sendImMsg(10000, userFDB.getUid(), 0, GlobalConstant.IMS_REMOVE_STOP, "");
                tp.execute(new RefreshUserThread(userService, sessionUser.getPartyId(), GlobalConstant.REFRESH_TYPE_USER));
//                tp.execute(new RefreshRoomByUidThread(roomService, String.valueOf(uid), null, false));
            }
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 启用用户信息
     *
     * @param uid
     * @return
     */
    @RequestMapping("/startUser")
    @ResponseBody
    public Json startUser(long uid) {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            UserBasic userFDB = userService.getUserBasicByUid(uid);
            if (userFDB.getPartyId().longValue() == sessionUser.getPartyId().longValue()) {
                userService.startUserBasic(sessionUser.getPartyId(), uid);
                userService.updateUserBasicVersion(userFDB.getUid());
                String uname = RedisHelper.getUname(uid);
                String opedInfo = "start user:" + uname;
                userService.saveSysBusiRecord(sessionUser, RecordType.WEBEXPIREDDATE, uid, uname, opedInfo, opedInfo);
                CmdUtil.sendImMsg(10000, userFDB.getUid(), 0, GlobalConstant.IMS_REMOVE_START, "");

                tp.execute(new RefreshUserThread(userService, sessionUser.getPartyId(), GlobalConstant.REFRESH_TYPE_USER));
            }
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/setLocation")
    @ResponseBody
    public Json setLocation(@RequestParam(value = "uids") long[] uids, Long flag, Long interval) {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            for (long uid : uids) {
                UserBasic userFDB = userService.getUserBasicByUid(uid);
                if (userFDB != null && sessionUser.getPartyId().longValue() == userFDB.getPartyId().longValue()) {
                    userFDB.setLocFlag(flag);
                    userFDB.setLocInterval(interval);
                    userService.updateLocationFlag(uid, flag, interval);
                    userService.updateUserBasicVersion(userFDB.getUid());
                    HashMap param = new HashMap();
                    param.put("flag", flag);
                    param.put("interval", interval);
                    CmdUtil.sendImMsg(10000, userFDB.getUid(), 0, GlobalConstant.GMS_MSG_TYPE_4000, JSONObject.toJSONString(param));
                }
            }
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 查询用户信息
     *
     * @param queryBean
     * @param pf
     * @return
     */
    @RequestMapping("/batchQueryUsers")
    @ResponseBody
    public Grid batchQueryUsers(UserBasic queryBean, PageFilter pf) {
        Grid grid = new Grid();
        try {
            UserBasic sessionUser = getSessionUser();
            queryBean.setPartyId(sessionUser.getPartyId());

            if (NumberUtils.isNullOrZero(queryBean.getOrgId())) {
                queryBean.setOrgId(sessionUser.getOrgId());
            }
            if (StringUtils.isNotBlank(queryBean.getUserName())) {
                queryBean.setUserName(URLDecoder.decode(queryBean.getUserName(), "UTF-8"));
                if (queryBean.getUserName().indexOf("_") >= 0) {
                    queryBean.setUserName(queryBean.getUserName().replaceAll("_", "\\\\_"));
                }
            }
            List<UserBasicVO> users = userService.queryUserBasicsBatch(queryBean, pf);
            long count = userService.countUserBasicsBySql(queryBean).longValue();
            grid.setData(users);
            grid.setCount(count);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setMsg(e.getMessage());
            grid.setCode(-9);
        }
        return grid;
    }

    /**
     * 查询用户信息
     *
     * @param queryBean
     * @param pf
     * @return
     */
    @RequestMapping("/queryUsers")
    @ResponseBody
    public Grid queryUsers(UserBasic queryBean, PageFilter pf) {
        Grid grid = new Grid();
        Date nowDate = new Date();
        try {
            UserBasic sessionUser = getSessionUser();
            queryBean.setPartyId(sessionUser.getPartyId());

            if (NumberUtils.isNullOrZero(queryBean.getOrgId())) {
                queryBean.setOrgId(sessionUser.getOrgId());
            }
            if (StringUtils.isNotBlank(queryBean.getUserName())) {
                queryBean.setUserName(URLDecoder.decode(queryBean.getUserName(), "UTF-8"));
                if (queryBean.getUserName().indexOf("_") >= 0) {
                    queryBean.setUserName(queryBean.getUserName().replaceAll("_", "\\\\_"));
                }
            }
            List<UserBasicVO> users = userService.queryUserBasicsBySql(queryBean, pf);
            if (!users.isEmpty()) {
                for (UserBasicVO user : users) {
                    if (user.getExpiredDate().getTime() > nowDate.getTime()) {
                        if (DateUtil.daysBetween(nowDate, user.getExpiredDate()) > 30) {
                            user.setIsExpried(2);
                        } else {
                            user.setIsExpried(1);
                        }
                    } else {
                        user.setIsExpried(0);
                    }
                }
            }
            long count = userService.countUserBasicsBySql(queryBean).longValue();
            grid.setData(users);
            grid.setCount(count);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setMsg(e.getMessage());
            grid.setCode(-9);
        }
        return grid;
    }

    /**
     * 查询组织信息
     *
     * @param queryBean
     * @param pf
     * @return
     */
    @RequestMapping("/queryOrgs")
    @ResponseBody
    public Grid queryOrgs(UserOrg queryBean, PageFilter pf) {
        Grid grid = new Grid();
        try {
            UserBasic sessionUser = getSessionUser();
            if (sessionUser != null) {
                queryBean.setPartyId(sessionUser.getPartyId());
                queryBean.setOrgCode(sessionUser.getOrgCode());
            }
            if (StringUtils.isNotBlank(queryBean.getOrgName())) {
                queryBean.setOrgName(URLDecoder.decode(queryBean.getOrgName(), "UTF-8"));
            }
            List<UserOrg> userOrgs = userService.queryUserOrgs(queryBean, pf);
            long count = userService.countUserOrgs(queryBean);
            grid.setData(userOrgs);
            grid.setCount(count);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setMsg(e.getMessage());
            grid.setCode(-9);
        }
        return grid;
    }


    /**
     * 根据上级组织编号查询组织信息
     *
     * @param parentId
     * @return
     */
    @RequestMapping("/queryOrgsByParentId")
    @ResponseBody
    public Grid queryOrgsByParentId(Long parentId) {
        Grid grid = new Grid();
        try {
            if (NumberUtils.isNullOrZero(parentId)) {
                UserBasic sessionUser = getSessionUser();
                if (sessionUser != null) {
                    parentId = sessionUser.getOrgId();
                }
            }
            List<UserOrg> orgs = userService.queryUserOrgsByParentId(parentId);
            grid.setRows(orgs);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setErrorMsg(e.getMessage());
            grid.setCode(-9);
        }
        return grid;
    }

    /**
     * 获取上级组织
     *
     * @return
     */
    @RequestMapping("/orgZTreeHave")
    @ResponseBody
    public List<ZTree> orgZTreeHave(String orgCode) throws Exception {

        List<ZTree> list = getOrgZtreeListHave(orgCode);
        return list;
    }

    /**
     * 获取上级组织树
     *
     * @return
     */
    private List<ZTree> getOrgZtreeListHave(String orgCodeName) throws Exception {
        List<ZTree> list = new ArrayList<ZTree>();
        UserBasic sessionUser = getSessionUser();
        String orgCode = "";
        long partyId = 0l;
        if (sessionUser != null) {

            orgCode = sessionUser.getOrgCode();
            partyId = sessionUser.getPartyId();

        }
        //部门添加上级组织时,去除自己作为上级组织和自己组织下的组织
        List<UserOrg> orgs = null;
        if (StringUtils.isNotBlank(orgCodeName)) {
            orgs = userService.queryParUserOrgsByOrgCodeC(orgCode, orgCodeName, partyId);
        }

        if (orgs != null) {
            for (UserOrg org : orgs) {
                ZTree tree = new ZTree();
                tree.setId(org.getOrgId());
                tree.setName(org.getOrgName());
                if (org.getParentId() != null && org.getParentId().longValue() > 0) {
                    tree.setpId(org.getParentId());
                    tree.setParent(true);
                } else {
                    tree.setParent(false);
                }
                tree.setOpen(true);
                list.add(tree);
            }
        }

        return list;
    }


    /**
     * 获取组织树
     *
     * @return
     */
    @RequestMapping("/orgZTree")
    @ResponseBody
    public List<ZTree> orgZTree(String orgCode) throws Exception {

        List<ZTree> list = getOrgZtreeList(orgCode);
        return list;
    }

    /**
     * 组织树
     *
     * @return
     */
    private List<ZTree> getOrgZtreeList(String orgCodeName) throws Exception {
        List<ZTree> list = new ArrayList<ZTree>();
        UserBasic sessionUser = getSessionUser();
        String orgCode = "";
        if (sessionUser != null) {
            orgCode = sessionUser.getOrgCode();
        }
        //部门添加上级组织时,去除自己作为上级组织
        List<UserOrg> orgs = null;
        if (StringUtils.isNotBlank(orgCodeName)) {
            orgs = userService.queryUserOrgsByOrgCodeC(orgCode, orgCodeName);
        } else {
            orgs = userService.queryUserOrgsByOrgCode(orgCode);
        }

        if (orgs != null) {
            for (UserOrg org : orgs) {
                ZTree tree = new ZTree();
                tree.setId(org.getOrgId());
                tree.setName(org.getOrgName());
                if (org.getParentId() != null && org.getParentId().longValue() > 0) {
                    tree.setpId(org.getParentId());
                    tree.setParent(true);
                } else {
                    tree.setParent(false);
                }
                tree.setOpen(true);
                list.add(tree);
            }
        }

        return list;
    }

    /**
     * 保存组织
     *
     * @param org
     * @return
     */
    @RequestMapping("/saveOrg")
    @ResponseBody
    public Json saveOrg(UserOrg org) {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();

            org.setPartyId(sessionUser.getPartyId());
            UserOrg orgFDB = userService.saveUserOrg(org);
            userService.updateUserOrgVersion(orgFDB.getOrgId());
            //刷新组织
            tp.execute(new RefreshUserThread(userService, sessionUser.getPartyId(), GlobalConstant.REFRESH_TYPE_ORG));
            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setI18nCode(e.getCode());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }


    /**
     * 根据组织编号查询组织信息
     *
     * @param orgId
     * @return
     */
    @RequestMapping("/getOrgByOrgId")
    @ResponseBody
    public Json getOrgByOrgId(long orgId) {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            UserOrg prisonOrgFDB = userService.queryUserOrgByOrgId(orgId);
            json.setObj(prisonOrgFDB);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 删除组织
     *
     * @param orgId
     * @return
     */
    @RequestMapping("/delOrg")
    @ResponseBody
    public Json delOrg(long orgId) {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            userService.delUserOrg(sessionUser.getPartyId(), orgId);
            userService.updateUserOrgVersion(orgId);
            //刷新组织
            tp.execute(new RefreshUserThread(userService, sessionUser.getPartyId(), GlobalConstant.REFRESH_TYPE_ORG));
            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setI18nCode(e.getCode());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }


    /**
     * 通过uid获取用户信息
     *
     * @param uid
     * @return
     */
    @RequestMapping("/getUserByUid")
    @ResponseBody
    public Json getUserByUid(long uid) {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            UserBasic userFDB = userService.getUserBasicByUid(uid);

            if (userFDB != null && sessionUser.getPartyId().longValue() == userFDB.getPartyId().longValue()) {
                userFDB.setOrgName(RedisHelper.getOrgName(userFDB.getOrgId()));

                //角色
                List<SecRole> secRoleList = userService.querySecRoleByUid(uid);
                if (secRoleList != null) {
                    List<Long> roids = new ArrayList<>();
                    for (SecRole role : secRoleList) {
                        roids.add(role.getRoid());
                    }
                    userFDB.setRoids(roids);
                }

                json.setObj(userFDB);
            }

            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 通过uid获取用户信息
     *
     * @param roid
     * @return
     */
    @RequestMapping("/getUsersByRoid")
    @ResponseBody
    public Json getUsersByRoid(long roid) {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            List<UserBasic> userFDB = userService.queryUserBasicsByRoid(roid);

            json.setObj(userFDB);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }


    /**
     * 批量删除用户信息
     * batchDelUser
     *
     * @param userBasics
     * @return
     */
    @RequestMapping("/batchDelUser")
    @ResponseBody
    public Json batchDelUser(@RequestBody List<UserBasic> userBasics) {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            String opedInfo = null;
            List<Long> delUserList = new ArrayList<>();
            if (!userBasics.isEmpty()) {
                for (UserBasic userBasic : userBasics) {
                    //删除用户
                    userService.delUserBasic(sessionUser.getPartyId(), userBasic.getUid());
                    userService.updateUserBasicVersion(userBasic.getUid());
                    roomService.delRoomMemberLogicallyByUid(userBasic.getUid());

                    opedInfo = "delete user:" + userBasic.getUserName();
                    userService.saveSysBusiRecord(sessionUser, RecordType.WEBEXPIREDDATE, userBasic.getUid(), userBasic.getUserName(), opedInfo, opedInfo);
                    delUserList.add(userBasic.getUid());
                }
            }
            if (!delUserList.isEmpty()) {
                String delUserIdStr = StringUtils.join(delUserList, ",");
            }
            tp.execute(new RefreshUserThread(userService, sessionUser.getPartyId(), GlobalConstant.REFRESH_TYPE_USER));
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }


    /**
     * 修改用户密码
     *
     * @param uid
     * @param password
     * @return
     */
    @RequestMapping("/updateUserPwd")
    @ResponseBody
    public Json updateUserPwd(long uid, String password) {
        Json json = new Json();
        try {
            if (StringUtils.isBlank(password)) {
                password = GlobalConstant.DEFAULT_PASSWORD;
            }
            UserBasic user = userService.getUserBasicByUid(uid);
            if (user == null) {
                String msg = I18NUtil.getMessage("WvApiController.chgUserPassword.error_systemError", null, Locale.getDefault());
                json.setMsg(msg);
                json.setI18nCode(I18nConstant.error_systemError);
            } else {
                String newPwd = Md5Util.Md5Encode(password, null);
                newPwd = Md5Util.Md5Encode(newPwd, null);
                user.setPassword(newPwd);
                userService.updUserPwd(user);
                userService.updateUserBasicVersion(uid);
                json.setSuccess(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }


    /**
     * 头像上传
     *
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping("/avaUpload")
    public Json avaFileUpload(@RequestParam("fileupload") MultipartFile file, long uid) {
        Json json = new Json();
        try {
            FileUtil.fileToLocal(file, uid, "_avatar.jpg");
            //更新头像版本号
            UserBasic userFDB = userService.getUserBasicByUid(uid);
            if (userFDB != null) {
                userFDB.setVFace(userFDB.getVFace() + 1);
                userService.saveUserBasic(userFDB);
                json.setSuccess(true);
            } else {
//                json.setMsg("未找到用户信息");
                String errorMsg = I18NUtil.getMessage("RoomApiController.getRooms.error_userNotExist", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_userNotExist, errorMsg);
            }
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }


    /**
     * SysStaticData静态表信息加载
     *
     * @return
     */
    @RequestMapping("/loadSysStaticData")
    @ResponseBody
    public Json loadSysStaticData() {
        Json json = new Json();
        try {
            json.setObj(LocalCacher.getAll(StaticDataCache.cacheId()));
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }


    /**
     * 用户数据生效
     *
     * @return
     */
    @RequestMapping("/userDataVal")
    @ResponseBody
    public Json userDataVal() {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            tp.execute(new RefreshUserThread(userService, sessionUser.getPartyId(), GlobalConstant.REFRESH_TYPE_USER));
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }


    /**
     * 组织Redis缓存刷新
     *
     * @return
     */
    @RequestMapping("/loadOrgRedis")
    @ResponseBody
    public Json loadOrgRedis() {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            UserOrg queryBean = new UserOrg();
            queryBean.setPartyId(sessionUser.getPartyId());
            List<UserOrg> userOrgs = userService.queryUserOrgs(queryBean, PageFilter.getMaxPageFilter());
            if (!userOrgs.isEmpty()) {
                for (UserOrg org : userOrgs) {
                    RedisHelper.setOrg(org.getOrgId(), JSONObject.toJSONString(org));
                }
            }
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 用户Redis缓存刷新
     *
     * @return
     */
    @RequestMapping("/loadUserRedis")
    @ResponseBody
    public Json loadUserRedis() {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            UserBasic queryBean = new UserBasic();
            queryBean.setPartyId(sessionUser.getPartyId());
            List<UserBasic> userBasics = userService.queryUserBasics(queryBean, PageFilter.getMaxPageFilter(), false);
            if (!userBasics.isEmpty()) {
                for (UserBasic user : userBasics) {
                    RedisHelper.setUser(user.getUid(), JSONObject.toJSONString(user));
                }
            }
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/getSession")
    @ResponseBody
    public Json getSession() {
        Json json = new Json();
        try {
            UserBasic user = getSessionUser();
            UserPartyCompany userPartyCompany = userService.getUserPartyCompanyByPartyId(user.getPartyId());
            UserOrg userOrg = userService.queryUserOrgByOrgId(user.getOrgId());
            List<SecFunction> functions = secService.getUserEnableFunction(user.getUid());
            List<String> roleList = new ArrayList<>();
            for (SecFunction function : functions) {
                roleList.add(function.getFuncDesc());
            }

            boolean alarm = false;
            boolean record = false;

            String companyFun = userPartyCompany.getFunction();
            if (StringUtils.isNotBlank(companyFun)) {
                if (companyFun.substring(0, 1).equals("1")) {
                    alarm = true;
                }
                if (companyFun.substring(1, 2).equals("1")) {
                    record = true;
                }
            }

            HashMap obj = new HashMap();
            obj.put("user", user);
            obj.put("userPartyCompany", userPartyCompany);
            obj.put("userOrg", userOrg);
            obj.put("functions", roleList);
            obj.put("alarm", alarm);
            obj.put("record", record);
            obj.put("supportAdminLoginApp", GlobalConstant.SUPPORT_ADMIN_LOGIN_APP);

            json.setObj(obj);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 获取频道资源详情
     *
     * @param uid
     * @param rid
     * @param startTime
     * @param endTime
     * @param resType
     * @param page
     * @param rows
     * @return
     */
    @ResponseBody
    @RequestMapping("getRoomResouces")
    public Grid getRoomResouces(Long uid, Long rid, Long orgId, String qryType, String startTime, String endTime, String resType, int page, int rows) {
        Grid grid = new Grid();
        try {
            UserBasic sessionUser = getSessionUser();

            if (NumberUtils.isNotNullOrZero(uid)) {
                UserBasic user = userService.getUserBasicByUid(sessionUser.getPartyId(), uid);
                if (user == null) {
//                    throw new Exception("uid参数错误");
                    String errorMsg = I18NUtil.getMessage("WvApiController.getChannelResouces.error_uId", null, Locale.getDefault());
                    throw new ViChatException(I18nConstant.error_parameter, errorMsg);
                }
            }

            String orgCode = null;
            if (qryType.equals("byChannel")) {
                orgId = 0L;
                if (NumberUtils.isNotNullOrZero(rid)) {
                    RoomBasic channel = roomService.getRoomBasicByRid(rid);
                    logger.info(channel.getPartyId() + "|" + sessionUser.getPartyId());
                    if (channel == null || channel.getPartyId().longValue() != sessionUser.getPartyId().longValue()) {
//                        throw new Exception("channelId数据错误");
                        String errorMsg = I18NUtil.getMessage("WvApiController.getChannelResouces.error_channelId", null, Locale.getDefault());
                        throw new ViChatException(I18nConstant.error_parameter, errorMsg);
                    }
                }
            } else if (qryType.equals("byOrg")) {
                rid = 0L;
                if (NumberUtils.isNotNullOrZero(orgId)) {
                    UserOrg org = userService.queryUserOrgByOrgId(orgId);
                    if (org == null) {
//                        throw new Exception("orgId数据错误");
                        String errorMsg = I18NUtil.getMessage("WvApiController.getChannelResouces.error_orgId", null, Locale.getDefault());
                        throw new ViChatException(I18nConstant.error_parameter, errorMsg);
                    } else {
                        orgCode = org.getOrgCode();
                    }
                }
            }

            List<VichatRoomRecResVO> resourceChannelDetails = resService.getVichatRoomRecResources(uid, rid, orgCode, startTime, endTime, resType, sessionUser.getPartyId(), page, rows);
            for (VichatRoomRecResVO val : resourceChannelDetails) {
                val.setUserName(RedisHelper.getUname(val.getUid()));
                if (qryType.equals("byOrg")) {
                    RoomBasic roomBasic = roomService.getRoomBasicByRid(val.getRid());
                    if (roomBasic != null) {
                        val.setRoomName(roomBasic.getName());
                    }
                }
            }
            grid.setRows(resourceChannelDetails);
        } catch (ViChatException e) {
            e.printStackTrace();
            grid.setErrorMsg(e.getMessage());
            grid.setI18nCode(e.getCode());
            grid.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setErrorMsg(e.getMessage());
            grid.setCode(-9);
        }
        return grid;
    }

    @RequestMapping("/getMainInfo")
    @ResponseBody
    public Json getMainInfo() {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            HashMap companyInfo = new HashMap();
            UserBasic userQryBean = new UserBasic();
            userQryBean.setOrgCode(sessionUser.getOrgCode());
            userQryBean.setPartyId(sessionUser.getPartyId());
            UserOnlineVO userCount = userService.getUserOnlineView(userQryBean);

            UserOrg orgQryBean = new UserOrg();
            orgQryBean.setOrgId(sessionUser.getOrgId());
            orgQryBean.setPartyId(sessionUser.getPartyId());
            long orgCount = userService.countUserOrgs(orgQryBean);

            RoomBasic roomQryBean = new RoomBasic();
            roomQryBean.setOrgCode(sessionUser.getOrgCode());
            roomQryBean.setPartyId(sessionUser.getPartyId());
            long channelCount = roomService.countRoomBasics(roomQryBean);

            UserPartyCompany queryUserPartyCompany = new UserPartyCompany();
            queryUserPartyCompany.setPartyId(sessionUser.getPartyId());
            long expiredCount = userService.countExpiredUser(queryUserPartyCompany).longValue();

            UserCompanyVO queryUserCompanyBean = new UserCompanyVO();
            queryUserCompanyBean.setPartyId(sessionUser.getPartyId());
            long expiringCount = userService.countExpiringUser(30, queryUserCompanyBean).longValue();

            companyInfo.put("userCount", userCount.getPartyUserNum());
            companyInfo.put("onlineCount", userCount.getOnlineUserNum());
            companyInfo.put("orgCount", orgCount);
            companyInfo.put("channelCount", channelCount);
            companyInfo.put("expiringCount", expiringCount);
            companyInfo.put("expiredCount", expiredCount);

            json.setObj(companyInfo);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/batchUpdateUserRole")
    @ResponseBody
    public Json batchUpdateUserRole(@RequestParam(value = "uids") long[] uids, Long roid) {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            for (long uid : uids) {
                UserBasic userFDB = userService.getUserBasicByUid(uid);
                if (userFDB != null && sessionUser.getPartyId().longValue() == userFDB.getPartyId().longValue() && userFDB.getUserType() != GlobalConstant.USER_TYPE_1) {
                    userService.saveUserSecRoleRel(uid, roid);
                    userService.updateUserBasicVersion(userFDB.getUid());
                }
            }
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/logout")
    @ResponseBody
    public Json logout() throws IOException {
        Json json = new Json();
        try {
            UserBasic userBasic = getSessionUser();
            RedisHelper.del("LOGIN_TOKEN:" + userBasic.getUid());//一小时超时
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 录音开关
     *
     * @param rid
     * @param recSwitch
     * @return
     */
    @RequestMapping("/switchRec")
    @ResponseBody
    public Json switchRec(long rid, String recSwitch) {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();

            //判断是否有修改权限
            UserPartyCompany userPartyCompany = userService.getUserPartyCompanyByPartyId(sessionUser.getPartyId());
            if (userPartyCompany != null) {
                RoomBasic roomBasicFDB = roomService.getRoomBasicByRid(rid);
                if (roomBasicFDB != null) {
                    long recSound = 0l;
                    String opedInfo = "close channel【" + roomBasicFDB.getName() + "】record swtich";
                    if (StringUtils.equals(recSwitch, "U")) {
                        recSound = 1l;
                        opedInfo = "open channel【" + roomBasicFDB.getName() + "】record switch";
                    }
                    try {
                        roomBasicFDB.setRecord(recSound);
                        roomService.setSwitchRecord(roomBasicFDB);
                        roomService.updateRoomBasicVersion(roomBasicFDB.getRid());
                    } catch (Exception ex) {
                        logger.error("修改频道录制开关出错");
                    }
                    SysStaticData srvData = staticDataService.getStaticData("RecSrvId", "default");
                    if (srvData != null) {
                        String srvIdsStr = srvData.getCodeName();
                        long[] srvIds = StringUtil.stringToLong(srvIdsStr.split(","));
                        SysRecord sysRecord = new SysRecord();
                        sysRecord.setRid(rid);
                        sysRecord.setRecState(recSwitch);
                        cfgService.saveSysRecord(sysRecord, srvIds);
                    }
                    // 操作日志
                    userService.saveSysBusiRecord(sessionUser, RecordType.WEBCHANNEL, sessionUser.getUid(), sessionUser.getUserName(), opedInfo, opedInfo);
                    json.setSuccess(true);
                }
            }
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 获取组织树用户
     *
     * @return
     */
    @RequestMapping("/orgZTreeUser")
    @ResponseBody
    public List<ZTree> orgZTreeUser(String searchName) {
        if (StringUtils.isNotBlank(searchName)) {
            try {
                searchName = URLDecoder.decode(searchName, "UTF-8");
                logger.info("searchName:" + searchName);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        List<ZTree> list = getOrgZtreeUserList(searchName);
        return list;
    }

    private List<ZTree> getOrgZtreeUserList(String searchName) {
        List<ZTree> list = null;
        try {
            list = new ArrayList<ZTree>();
            UserBasic sessionUser = getSessionUser();
            UserOrg orgQueryBean = new UserOrg();

            if (StringUtils.isNotBlank(searchName)) {
                searchName = URLDecoder.decode(searchName, "UTF-8");
                if (searchName.indexOf("_") >= 0) {
                    searchName = searchName.replaceAll("_", "\\\\_");
                }
            }

            orgQueryBean.setPartyId(sessionUser.getPartyId());
            orgQueryBean.setOrgId(sessionUser.getOrgId());
            if (StringUtils.isNotBlank(searchName)) {
                orgQueryBean.setOrgName(searchName);
            }
            PageFilter pf = PageFilter.getMaxPageFilter();
            List<UserOrg> orgs = userService.queryUserOrgs(orgQueryBean, pf);
            if (!orgs.isEmpty()) {
                for (UserOrg org : orgs) {
                    ZTree orgTree = new ZTree();
                    orgTree.setId(org.getOrgId());
                    orgTree.setpId(org.getParentId());
                    orgTree.setName(org.getOrgName());
                    orgTree.setOpen(false);
                    list.add(orgTree);
                    UserBasic queryUserBean = new UserBasic();
                    queryUserBean.setPartyId(sessionUser.getPartyId());
                    queryUserBean.setOrgId(org.getOrgId());
                    queryUserBean.setDisplayState(99l);
                    List<UserBasic> UserBasics = userService.queryUserBasics(queryUserBean, pf, true);
                    if (!UserBasics.isEmpty()) {
                        for (UserBasic val : UserBasics) {
                            if (val.getOrgId().longValue() == org.getOrgId().longValue()) {
                                ZTree uTree = new ZTree();
                                uTree.setId(val.getUid());
                                uTree.setpId(org.getOrgId());
                                uTree.setName(val.getUserName());
                                if (val.getDisplayState() == GlobalConstant.DISPLAY_STATE_1) {
                                    uTree.setOnline(true);
                                } else {
                                    uTree.setOnline(false);
                                }
                                uTree.setUser(true);
                                list.add(uTree);
                            }
                        }
                    }
                }
            } else {
                UserBasic queryUserBean = new UserBasic();
                queryUserBean.setPartyId(sessionUser.getPartyId());
                queryUserBean.setUserName(searchName);
                queryUserBean.setDisplayState(99l);
                List<UserBasic> UserBasics = userService.queryUserBasics(queryUserBean, pf, true);
                if (!UserBasics.isEmpty()) {
                    for (UserBasic val : UserBasics) {
                        ZTree uTree = new ZTree();
                        if (val.getDisplayState() == GlobalConstant.DISPLAY_STATE_1) {
                            uTree.setOnline(true);
                        } else {
                            uTree.setOnline(false);
                        }
                        uTree.setId(val.getUid());
                        uTree.setName(val.getUserName());
                        uTree.setUser(true);
                        list.add(uTree);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @RequestMapping("/batchUpdateUserOrg")
    @ResponseBody
    public Json batchUpdateUserOrg(@RequestParam(value = "uids") long[] uids, Long orgId) {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            for (long uid : uids) {
                UserBasic userFDB = userService.queryUserBasicByUid(uid);
                if (userFDB != null && sessionUser.getPartyId().longValue() == userFDB.getPartyId().longValue()) {
                    userService.saveUserOrg(userFDB, orgId);
                    userService.updateUserBasicVersion(userFDB.getUid());
                }
            }
            tp.execute(new RefreshUserThread(userService, sessionUser.getPartyId(), GlobalConstant.REFRESH_TYPE_USER));
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/batchUpdateUserExpiredDate")
    @ResponseBody
    public Json batchUpdateUserExpiredDate(@RequestParam(value = "uids") long[] uids, Integer monthNumber) {
        Json json = new Json();
        try {

            UserBasic sessionUser = getSessionUser();
            String opedInfo = null;
            List<Long> errorList = new ArrayList<>();
            long partyId = 0;

            UserPartyCompany companyFDB = userService.getUserPartyCompanyByPartyId(sessionUser.getPartyId());
            if (companyFDB != null) {
                long result = monthNumber * uids.length;
                if (NumberUtils.isNullOrZero(companyFDB.getAuthMonth())) {
                    String errorMsg = I18NUtil.getMessage("error_balanceNotEnough", null, Locale.getDefault());
                    throw new ViChatException(I18nConstant.error_balanceNotEnough, errorMsg);
                } else {
                    if (companyFDB.getAuthMonth() - result < 0) {//余额判断
                        String errorMsg = I18NUtil.getMessage("error_balanceNotEnough", null, Locale.getDefault());
                        throw new ViChatException(I18nConstant.error_balanceNotEnough, errorMsg);
                    }
                }
            } else {
                String errorMsg = I18NUtil.getMessage("error_agentCompanyNotExist", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_agentCompanyNotExist, errorMsg);
            }

            for (long id : uids) {
                UserBasic userFDB = userService.queryUserBasicByUid(id);
                Date newExpiredDate = DateUtil.addMonth(userFDB.getExpiredDate(), monthNumber);
                opedInfo = "extend user expiration date to :" + newExpiredDate + ", user name :" + userFDB.getUserName();

                if (newExpiredDate.after(DateUtil.getDateByString("2038-01-01 00:00:00"))) {
                    errorList.add(id);
                    continue;
                }

                userService.updateExpiredDate(sessionUser, userFDB, monthNumber);
                userService.saveSysBusiRecord(sessionUser, RecordType.WEBEXPIREDDATE, id, userFDB.getUserName(), opedInfo, opedInfo);

                partyId = userFDB.getPartyId();
            }

            if (NumberUtils.isNotNullOrZero(partyId)) {
                userService.updateUserBasicVersionByPartyId(partyId);
            }
            if (!errorList.isEmpty()) {
                new ViChatException(I18nConstant.error_overMaxExpriedDate, errorList.toString());
            }
            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/getSecRoleByUid")
    @ResponseBody
    public Json getSecRoleByUid(Long uid) {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            UserBasic userFDB = userService.getUserBasicByUid(uid);
            if (userFDB != null && sessionUser.getPartyId().longValue() == userFDB.getPartyId().longValue() && userFDB.getUserType() != GlobalConstant.USER_TYPE_1) {
                List<SecRole> secRole = userService.querySecRoleByUid(uid);
                json.setObj(secRole.get(0));
            }
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/batchCheckUsers")
    @ResponseBody
    public Json batchCheckUsers(@RequestBody JSONObject userBasicsObj) {
        Json json = new Json();
        String errorCode = null;
        try {
            List<UserBasic> userBasics = userBasicsObj.getJSONArray("userBasics").toJavaList(UserBasic.class);
            long partyId = userBasicsObj.getLongValue("partyId");

            if (NumberUtils.isNullOrZero(partyId)) {
//                throw new Exception("请求参数不正确");
                String errorMsg = I18NUtil.getMessage("error_parameter", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_parameter, errorMsg);
            }

            if (!userBasics.isEmpty()) {
                ArrayList<UserBasic> successUsers = new ArrayList<UserBasic>();
                ArrayList<UserBasic> errorUsers = new ArrayList<UserBasic>();
                Set<String> accountSet = new HashSet<>();
                Set<String> iccidSet = new HashSet<>();
                Set<String> imeiSet = new HashSet<>();
                for (UserBasic user : userBasics) {
                    UserOrg rootOrg = userService.getRootOrgByPartyId(partyId);
                    if (rootOrg == null) {
                        json.setI18nCode(I18nConstant.error_orgNotExist);
                        throw new Exception("数据异常，该企业组织信息错误,无根组织。请联系管理员处理，谢谢。");
                    }

                    errorCode = UserBasic.checkUserBasic(user);
                    if (errorCode != null) {
                        user.setExt1(errorCode);
                        errorUsers.add(user);
                        continue;
                    }

                    if (StringUtils.isNotBlank(user.getTerminal())) {
                        boolean isTerminalExist = userService.isTerminalExist(user.getTerminal());
                        if (isTerminalExist) {
                            user.setExt1(I18nConstant.error_accountIsExist);
                            errorUsers.add(user);
                            continue;
                        }
                        if (accountSet.contains(user.getTerminal())) {
                            user.setExt1(I18nConstant.error_accountIsExist);
                            errorUsers.add(user);
                            continue;
                        }
                    }
                    if (StringUtils.isNotBlank(user.getIccid())) {
                        boolean isIccidExist = userService.isIccidExist(user.getIccid());
                        user.setTerminal(user.getIccid());
                        if (isIccidExist) {
                            user.setExt1(I18nConstant.error_ICCIDIsExist);
                            errorUsers.add(user);
                            continue;
                        }
                        if (iccidSet.contains(user.getIccid())) {
                            user.setExt1(I18nConstant.error_ICCIDIsExist);
                            errorUsers.add(user);
                            continue;
                        }
                    }
                    if (StringUtils.isNotBlank(user.getImei())) {
                        boolean isImeiExist = userService.isImeiExist(user.getImei());
                        user.setTerminal(user.getImei());
                        if (isImeiExist) {
                            user.setExt1(I18nConstant.error_IMEIIsExist);
                            errorUsers.add(user);
                            continue;
                        }
                        if (imeiSet.contains(user.getImei())) {
                            user.setExt1(I18nConstant.error_IMEIIsExist);
                            errorUsers.add(user);
                            continue;
                        }
                    }
                    if (StringUtils.isBlank(user.getTerminal()) && StringUtils.isBlank(user.getIccid()) && StringUtils.isBlank(user.getImei())) {
                        user.setExt1(I18nConstant.error_parameter);
                        errorUsers.add(user);
                        continue;
                    }

                    if (StringUtils.isNotBlank(user.getOrgName())) {
                        String orgName = URLDecoder.decode(user.getOrgName(), "UTF-8");
                        List<UserOrg> userOrgList = userService.queryUserOrgByOrgName(partyId, orgName);
                        if (userOrgList == null || userOrgList.size() == 0) {
                            user.setExt1(I18nConstant.error_orgNotExist);
                            errorUsers.add(user);
                            continue;
                        } else if (userOrgList.size() == 1) {
                            UserOrg org = userOrgList.get(0);
                            user.setOrgId(org.getOrgId());
                            user.setOrgCode(org.getOrgCode());
                            user.setOrgName(org.getOrgName());
                            user.setPartyId(partyId);
                        } else if (userOrgList.size() == 2) {
                            user.setExt1(I18nConstant.error_orgNotUnique);
                            errorUsers.add(user);
                            continue;
                        }
                    } else {
                        user.setOrgId(rootOrg.getOrgId());
                        user.setOrgCode(rootOrg.getOrgCode());
                        user.setOrgName(rootOrg.getOrgName());
                        user.setPartyId(partyId);
                    }
                    //到这里已经通过层层校验
                    accountSet.add(user.getTerminal());
                    iccidSet.add(user.getIccid());//空值无所谓，一起加入set中
                    imeiSet.add(user.getImei());//空值无所谓，一起加入set中
                    successUsers.add(user);//先加到list中
                }
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("successUsers", successUsers);
                jsonObject.put("errorUsers", errorUsers);
                json.setObj(jsonObject);
            }
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setSuccess(false);
        }
        return json;
    }

    @RequestMapping("/batchSaveUserBasic")
    @ResponseBody
    public Json batchSaveUserBasic(@RequestBody List<UserBasic> user) throws IOException {
        Json json = new Json();
        try {
            Map<String, List<UserBasic>> resultMap = userService.batchCreateUser(user);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("successUsers", resultMap.get("SUCCESS_LIST"));
            jsonObject.put("errorUsers", resultMap.get("FAIL_LIST"));
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setSuccess(false);
            json.setMsg(e.getMessage());
        }
        return json;
    }

    @RequestMapping("/queryRoomMicRecord")
    @ResponseBody
    public Grid queryRoomMicRecord(@RequestBody RoomMicRecordDLog micRecordDLog, PageFilter pageFilter) {
        Grid grid = new Grid();
        try {
            UserBasic session = getSessionUser();
            micRecordDLog.setPartyId(session.getPartyId());
            if (micRecordDLog.getQueryDate() == null) {
                micRecordDLog.setQueryDate(new Date());
            }
            List<RoomMicRecordDLog> recordDLogs = resService.queryRoomMicRecord(micRecordDLog, pageFilter);
            for (RoomMicRecordDLog recordFDB : recordDLogs) {
                recordFDB.setUserName(RedisHelper.getUname(recordFDB.getUid()));

                RoomBasic roomBasic = roomService.getRoomBasicByRid(recordFDB.getRid());
                if (roomBasic != null) {
                    recordFDB.setRoomName(roomBasic.getName());
                }
            }
            long count = resService.countRoomMicRecord(micRecordDLog).longValue();
            grid.setData(recordDLogs);
            grid.setCount(count);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setMsg(e.getMessage());
            grid.setCode(-9);
        }
        return grid;
    }

    @RequestMapping("/queryRechargeRecordCompany")
    @ResponseBody
    public Grid queryRechargeRecordCompany(@RequestBody RechargeRecord rechargeRecord, PageFilter pageFilter) {
        Grid grid = new Grid();
        try {
            UserBasic sessionUser = getSessionUser();
            rechargeRecord.setObj1Type(3L);
            rechargeRecord.setObj1PartyId(sessionUser.getPartyId());
            List<RechargeRecord> rechargeRecordList = userService.queryRechargeRecord(rechargeRecord, pageFilter);
            long count = userService.countRechargeRecord(rechargeRecord);

            grid.setData(rechargeRecordList);
            grid.setCount(count);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setMsg(e.getMessage());
            grid.setCode(-9);
        }
        return grid;
    }

    @RequestMapping("/setRechargeRecordRemark")
    @ResponseBody
    public Json setRechargeRecordRemark(Long logId, String remark) {
        Json json = new Json();
        try {
            if (NumberUtils.isNullOrZero(logId)) {
                String errorMsg = I18NUtil.getMessage("error_parameter", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_parameter, errorMsg);
            }
            userService.setRechargeRecordRemark(logId, remark);

            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/queryUserBasicToRoom")
    @ResponseBody
    public Grid queryUserBasicToRoom(UserBasic queryBean) {
        Grid grid = new Grid();
        try {
            UserBasic sessionUser = getSessionUser();
            queryBean.setPartyId(sessionUser.getPartyId());

            if (StringUtils.isNotBlank(queryBean.getUserName())) {
                queryBean.setUserName(URLDecoder.decode(queryBean.getUserName(), "UTF-8"));
                if (queryBean.getUserName().indexOf("_") >= 0) {
                    queryBean.setUserName(queryBean.getUserName().replaceAll("_", "\\\\_"));
                }
            }
            queryBean.setDisplayState(null);

            String userType = null;
            if (!GlobalConstant.SUPPORT_ADMIN_LOGIN_APP) {
                userType = "3,4";
            }
            List<UserBasicVO> users = userService.queryUserBasicToRoom(queryBean, PageFilter.getMaxPageFilter(), userType);
            Long count = userService.countUserBasicToRoom(queryBean).longValue();
            grid.setData(users);
            grid.setCount(count);
        } catch (ViChatException e) {
            e.printStackTrace();
            grid.setMsg(e.getMessage());
            grid.setI18nCode(e.getCode());
            grid.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setCode(-9);
        }
        return grid;
    }

    @RequestMapping("/queryRechargeRecordPartyCompany")
    @ResponseBody
    public Grid queryRechargeRecordPartyCompany(@RequestBody RechargeRecord rechargeRecord, PageFilter pageFilter) {
        Grid gridR = new Grid();
        try {
            UserBasic sessionUser = getSessionUser();
            rechargeRecord.setObj1PartyId(sessionUser.getPartyId());
            rechargeRecord.setObj1Type(4L);
            List<RechargeRecord> rechargeRecordList = userService.queryRechargeRecord(rechargeRecord, pageFilter);
            long count = userService.countRechargeRecord(rechargeRecord);

            gridR.setData(rechargeRecordList);
            gridR.setCount(count);
        } catch (Exception e) {
            e.printStackTrace();
            gridR.setMsg(e.getMessage());
            gridR.setCode(-9);
        }
        return gridR;
    }

    @RequestMapping("/verificationPassword")
    @ResponseBody
    public Json verificationPassword(String password) {
        Json jsonR = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            password = Md5Util.Md5Encode(password, null);
            password = Md5Util.Md5Encode(password, null);
            if (!StringUtils.equals(sessionUser.getPassword(), password)) {
                String errorMsg = I18NUtil.getMessage("error_pwdError", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_pwdError, errorMsg);
            }
            jsonR.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            jsonR.setMsg(e.getMessage());
            jsonR.setI18nCode(e.getCode());
            jsonR.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            jsonR.setMsg(e.getMessage());
            jsonR.setCode(-9);
        }
        return jsonR;
    }

    /**
     * 查询操作日志
     *
     * @return
     */
    @RequestMapping("/querySysBusiRecord")
    @ResponseBody
    public Grid querySysBusiRecord(SysBusiRecord queryBean, PageFilter pageFilter) {
        Grid grid = new Grid();
        try {
            UserBasic sessionUser = getSessionUser();
            if (NumberUtils.isNullOrZero(queryBean.getOrgId())) {
                queryBean.setOrgId(sessionUser.getPartyId());
            }
            List<SysBusiRecord> userMsgs = userService.querySysBusiRecord(queryBean, pageFilter);
            if (userMsgs != null) {
                for (SysBusiRecord sysBusiRecord : userMsgs) {
                    sysBusiRecord.setOrgName(RedisHelper.getOrgName(sysBusiRecord.getOrgId()));
                }
            }
            long count = userService.countSysBusiRecord(queryBean);
            grid.setData(userMsgs);
            grid.setCount(count);
            grid.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setMsg(e.getMessage());
            grid.setCode(-9);
        }
        return grid;
    }

    @RequestMapping("/querySystemMessage")
    @ResponseBody
    public Grid querySystemMessage(SystemMessage queryBean, PageFilter pageFilter) {
        Grid grid = new Grid();
        try {
            UserBasic sessionUser = getSessionUser();
            queryBean.setUid(sessionUser.getUid());
            List<SystemMessage> systemMessages = systemMessageService.querySystemMessage(queryBean, pageFilter);
            if (systemMessages != null) {
                for (SystemMessage message : systemMessages) {
                    message.setMsgJson(null);
                }
            }
            Long count = systemMessageService.countSystemMessage(queryBean).longValue();
            grid.setData(systemMessages);
            grid.setCount(count);
        } catch (ViChatException e) {
            e.printStackTrace();
            grid.setMsg(e.getMessage());
            grid.setI18nCode(e.getCode());
            grid.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setCode(-9);
        }
        return grid;
    }

    /**
     * 保存子账号
     *
     * @return
     */
    @RequestMapping("/saveSystemMessage")
    @ResponseBody
    public Json saveSystemMessage(@RequestBody SystemMessage queryBean) {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            if (queryBean.getMsgIds() != null && !queryBean.getMsgIds().isEmpty()) {
                for (Long msgId : queryBean.getMsgIds()) {
                    SystemMessage messageFDB = systemMessageService.querySystemMessageByMsgId(msgId);
                    if (messageFDB != null && messageFDB.getUid().longValue() == sessionUser.getUid().longValue()) {
                        messageFDB.setIsReceive(queryBean.getIsReceive());
                        messageFDB.setIsRead(queryBean.getIsRead());
                        systemMessageService.saveSystemMessage(messageFDB);
                    }
                }
            }
            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 保存子账号
     *
     * @return
     */
    @RequestMapping("/delSystemMessage")
    @ResponseBody
    public Json delSystemMessage(@RequestBody SystemMessage queryBean) {
        Json json = new Json();
        try {
            UserBasic sessionUser = getSessionUser();
            if (queryBean.getMsgIds() != null && !queryBean.getMsgIds().isEmpty()) {
                for (Long msgId : queryBean.getMsgIds()) {
                    SystemMessage messageFDB = systemMessageService.querySystemMessageByMsgId(msgId);
                    if (messageFDB != null && messageFDB.getUid().longValue() == sessionUser.getUid().longValue()) {
                        systemMessageService.delSystemMessage(messageFDB.getMsgId());
                    }
                }
            }
            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/countUnreadMessage")
    @ResponseBody
    public Json countUnreadMessage() {
        Json json = new Json();
        try {
            UserBasic userBasic = getSessionUser();
            SystemMessage queryBean = new SystemMessage();
            queryBean.setUid(userBasic.getUid());
            queryBean.setIsRead(0L);
            long conut = systemMessageService.countSystemMessage(queryBean);
            json.setMsg(String.valueOf(conut));
            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/allReadedMessage")
    @ResponseBody
    public Json allReadedMessage() {
        Json json = new Json();
        try {
            UserBasic userBasic = getSessionUser();
            SystemMessage queryBean = new SystemMessage();
            queryBean.setUid(userBasic.getUid());
            queryBean.setIsRead(0L);
            List<SystemMessage> systemMessages = systemMessageService.querySystemMessage(queryBean, PageFilter.getMaxPageFilter());
            if (systemMessages != null) {
                for (SystemMessage systemMessageFDB : systemMessages) {
                    systemMessageFDB.setIsRead(1L);
                    systemMessageFDB.setIsReceive(1L);
                    systemMessageService.saveSystemMessage(systemMessageFDB);
                }
            }
            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 查询执法取证
     *
     * @param queryBean
     * @param pageFilter
     * @return
     * @throws Exception
     */
    @RequestMapping("/getResEvent")
    @ResponseBody
    public Grid queryResEventToEvidence(@RequestBody ResEvent queryBean, PageFilter pageFilter) throws Exception {
        Grid grid = new Grid();

        try {
            UserBasic sessionUser = getSessionUser();
            queryBean.setPartyId(sessionUser.getPartyId());

            queryBean.setEvtType(GlobalConstant.EVT_TYPE_EVIDENCE);
            if (NumberUtils.isNullOrZero(queryBean.getUid()) || queryBean.getUid().longValue() == sessionUser.getUid().longValue()) {
                queryBean.setUid(sessionUser.getUid());
            } else {
                queryBean.setQueryUid(queryBean.getUid());
            }
            queryBean.setRptUid(sessionUser.getUid());
            queryBean.setRptOrgCode(sessionUser.getOrgCode());
            queryBean.setRemindUids(String.valueOf(sessionUser.getUid()));

            List<ResEvent> resEventList = resService.queryResEvent(queryBean, pageFilter);
            if (resEventList != null) {
                for (ResEvent resEvent : resEventList) {
                    if (NumberUtils.isNotNullOrZero(resEvent.getRptOrgId())) {
                        resEvent.setRptOrgName(RedisHelper.getOrgName(resEvent.getRptOrgId()));
                    }
                    if (NumberUtils.isNotNullOrZero(resEvent.getRptUid())) {
                        resEvent.setRptUserName(RedisHelper.getUname(resEvent.getRptUid()));
                    }

                    if (StringUtils.isNotBlank(resEvent.getRemindUids())) {
                        String userNames = UserUtil.getUserNamesByJson(resEvent.getRemindUids());
                        resEvent.setRemindUserName(userNames);
                    }


                    //文件
                    List<ResFile> files = resService.getFileListByEventId(resEvent.getEvtId());
                    if (files != null) {
                        List<ResFileVO> resFileVOS = new ArrayList<>();
                        for (ResFile file : files) {
                            ResFileVO fileVO = new ResFileVO();
                            fileVO.setResId(file.getResId());
                            fileVO.setStoreUrl("" + file.getStoreUrl());
                            fileVO.setResType(file.getResType());
                            fileVO.setL(file.getL());
                            resFileVOS.add(fileVO);
                        }
                        resEvent.setFileVOList(resFileVOS);
                    }
                    resEvent.setUserName(RedisHelper.getUname(resEvent.getUid()));
                }
            }
            long count = resService.countResEvent(queryBean);

            grid.setData(resEventList);
            grid.setCount(count);
            grid.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setErrorMsg(e.getMessage());
            grid.setCode(-9);
        }
        return grid;
    }
}
